package com.holly.common.help;

import android.text.TextUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * @author Joey Huang（QQ:273179370）
 * @created 2016/8/5
 */
public class NumberFormat {
    public static final int HALF_UP =1;

    //保留小数位数
    private int roundSize = 2;

    private Object mValue;

    public NumberFormat(Object value) {
        this.mValue = value;
    }

    public String toString(int pointSize,int mode) {
        Double d = Double.parseDouble(String.valueOf(mValue));
        if (d.isNaN()) {
            return "";
        }
        BigDecimal b = new BigDecimal(d);
        switch (mode) {
            case HALF_UP:
                double v = b.setScale(pointSize, RoundingMode.HALF_UP).doubleValue();
                return String.valueOf(v);
            default:
                return "";
        }
    }

    //四舍五入
    public double getDoubleByRound(Double f) {
        BigDecimal b = new BigDecimal(f);
        return b.setScale(roundSize, RoundingMode.HALF_UP).doubleValue();
    }

    public double getDoubleByRound(String f) {
        if (TextUtils.isEmpty(f)) {
            return 0;
        }
        try {
            double v = Double.parseDouble(f);
            return getDoubleByRound(v);
        } catch (Exception e) {
            return 0;
        }
    }

    public String getStringByRound(String f) {
        if (TextUtils.isEmpty(f)) {
            return "";
        }
        try {
            double v = Double.parseDouble(f);
            String str = String.valueOf(getDoubleByRound(v));
            if (!str.contains(".")) {
                str += ".";
                for (int i = 0; i < roundSize; i++) {
                    str += "0";
                }
                return str;
            } else {
                int pointWei = str.length() - str.indexOf(".");
                for (int i = pointWei; i < roundSize; i++) {
                    str += "0";
                }
                return str;
            }
        } catch (Exception e) {
            return "";
        }
    }

    public String getStringByDouble(double f) {
        double v = getDoubleByRound(f);
        return String.valueOf(v);
    }

}
